package thirdMax;

import java.util.TreeSet;

//public class Solution {
//    public int thirdMax(int[] nums) {
////        Arrays.sort(nums);
////        if(nums.length<3){
////            return nums[nums.length-1];
////        }
////        int index = 0;
////        int i;
////        int prev = nums[nums.length-1];
////        for (i = nums.length-2; i >=0 ; i--) {
////            if(nums[i]!=prev){
////                index++;
////                prev = nums[i];
////            }
////            if(index==3){
////                break;
////            }
////        }
////        if(index!=3){
////            return nums[nums.length-1];
////        }
////        return nums[i];
//    }
//}
class Solution {
    public int thirdMax(int[] nums) {
        TreeSet<Integer> s = new TreeSet<Integer>();
        for (int num : nums) {
            s.add(num);
            if (s.size() > 3) {
                s.remove(s.first());
            }
        }
        return s.size() == 3 ? s.first() : s.last();
    }
}

